var xlsx = require('node-xlsx')
var fs = require('fs')
var path = require('path')
// require('../../home-work/治愈系课后翻译作业/1. 时态/时态作业1.xlsx')
// const buffer = path.resolve(__dirname, '../../home-work/治愈系课后翻译作业/1. 时态/时态作业1.xlsx')
// const workSheetsFromBuffer = xlsx.parse(buffer)
// fs.writeFileSync(path.resolve(__dirname, './test.json'), JSON.stringify(formatSheets(workSheetsFromBuffer), null, 2))
// console.log(typeof workSheetsFromBuffer)

var commonPath = '../../home-work/治愈系课后翻译作业'
var configPath = {
  tense: '1. 时态'
}
// var f = fs.readdirSync(resolve([commonPath]))
// console.log(f)
main()
// fs.writeFileSync(resolve(['./test/test.js']), '123')
function main() {
  fs.readdirSync(resolve([commonPath])).forEach(dir => {
    write(dir)
  })
  // fs.writeFileSync(resolve([`./${conf.dirKey}.json`]), JSON.stringify(conf, null, 2))
  console.log('写入成功!')
}

function write(dir) {
  var conf = getOutPutConfig(dir)
  conf.filesName.forEach(name => {
    const parsePath = resolve([commonPath, conf.dirName, `./${name}.xlsx`])
    const workSheetsFromBuffer = xlsx.parse(parsePath)
    const data = JSON.stringify(formatSheets(workSheetsFromBuffer), null, 2)
    const pagePath =  resolve([`./${conf.dirName}`])
    const writePath = resolve([pagePath, `./${name}.json`])
    try {
      fs.statSync(pagePath)
    } catch (e) {
      fs.mkdirSync(resolve([pagePath]))
    }
    // fs.stat(pagePath, (err, d) => {console.log(err, d)})
    // fs.mkdirSync(resolve([pageName]))
    fs.writeFileSync(writePath, data)
  })
}

// 获得输入参数
function getOutPutConfig(dir) {
  if(dir == null) process.exit()
  var filesName = fs.readdirSync(resolve([commonPath, dir]))
  var arr = []
  filesName.forEach((name) => {
    if (!/^~/.test(name)) {
      arr.push(name.replace('\.xlsx', ''))
    }
  })
  return {
    dirName: dir,
    filesName: arr
  }
}
// console.log(getOutPutConfig())
// 格式化sheets
function formatSheets(sheets) {
  const arr = []
  sheets[0].data.forEach((item, index) => {
    if(typeof item[0] === 'number') {
      let zh = ''
      let en = ''
      item.forEach(child => {
        if (isNaN(+child)) {
          /[a-z]/ig.test(child) ? en += ' ' + child.trim() : zh += child
        }
      })
      arr.push({
        key: index,
        zh,
        en
      })
    }
  })
  sheets[0].data = arr
  return sheets[0]
}

// 路径
function resolve(p) {
  return path.resolve(__dirname, ...p)
}
